import React, {useEffect, useState} from 'react';
import {Modal, Table, Button, message} from 'antd';
import {getClassStudentInfo, removeClassStudent} from "../../../api/classInfo.js";
const StudentInClassModal = ({ visible, onCancel, checkClass}) => {
    const [data,setData] = useState([]);
    const [loading, setLoading] = useState(false);

    const fetchAcademyInfo = async () => {
        setLoading(true);
        try {
            const res = await getClassStudentInfo(checkClass.classId);
            setData(res.data);
        } catch (error) {
            message.error('获取学生信息失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            fetchAcademyInfo();
        }
    }, [visible, checkClass]);

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, record, index) => index + 1,
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            align: 'center',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            align: 'center',
        },
        {
            title: '性别',
            dataIndex: 'gender',
            align: 'center',
            render: (gender) => (gender === 1 ? '男' : '女'),
        },
        {
            title: '年龄',
            dataIndex: 'age',
            align: 'center',
        },
        {
            title: '年级',
            dataIndex: 'grade',
            align: 'center',
        },
        {
            title: '操作',
            align: 'center',
            render: (_, record) => (
                <Button type="link" danger onClick={() => removeStudent(record.id)}>
                    移出班级
                </Button>
            ),
        },
    ];

    const removeStudent = (id) => {
        const res = removeClassStudent({
            studentId: id
        });
        if (res.code === 200) {
            fetchAcademyInfo();
            message.success("移出成功");
        }
    }

    return (
        <Modal
            title="班级学生列表"
            open={visible}
            onCancel={onCancel}
            footer={null}
            width={900}
            loading={loading}
        >
            <Table
                dataSource={data}
                columns={columns}
                rowKey="id"
                pagination={{ pageSize: 8 }}
            />
        </Modal>
    );
};

export default StudentInClassModal;